package com.xmall.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.define.base.ResultCode;
import com.xmall.define.dto.sys.DictValueDto;
import com.xmall.exception.XmallException;
import com.xmall.sys.define.request.dict.DictValueUpdateRequest;
import com.xmall.sys.entity.DictValue;
import com.xmall.sys.mapper.DictValueMapper;
import com.xmall.sys.service.IDictService;
import com.xmall.sys.service.IDictValueService;
import com.xmall.sys.service.other.IMsgService;
import com.xmall.sys.utils.ConvertUtils;
import com.xmall.utils.XmallUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 字典值表 服务实现类
 * </p>
 *
 * @author xmall
 * @since 2023-12-05
 */
@Service
public class DictValueServiceImpl extends ServiceImpl<DictValueMapper, DictValue> implements IDictValueService {

    @Resource
    private IMsgService msgService;

    @Resource
    private IDictService dictService;

    /**
     * 详情
     */
    @Override
    public DictValueDto info(Long id) {
        DictValue entity = this.getById(id);
        XmallUtils.notNull(entity);
        return ConvertUtils.DictModule.INSTANCE.toValueDto(entity);
    }

    /**
     * 列表
     */
    @Override
    public List<DictValueDto> list(Long dictId) {
        List<DictValue> dictValueList = this.list(new QueryWrapper<DictValue>().eq("dict_id", dictId));
        return ConvertUtils.DictModule.INSTANCE.toValueDtoList(dictValueList);
    }

    /**
     * 新增
     */
    @Override
    public void saveEntity(DictValueUpdateRequest request) {
        long count = this.count(new QueryWrapper<DictValue>().eq("dict_id", request.getDictId()).eq("code", request.getCode()));
        if(count > 0) {
            throw new XmallException(ResultCode.SYS_DICT_CODE_EXIST);
        }
        this.save(ConvertUtils.DictModule.INSTANCE.toValueEntity(request));
    }

    /**
     * 编辑
     */
    @Override
    public void updateEntity(DictValueUpdateRequest request) {
        DictValue entity = this.getById(request.getId());
        XmallUtils.notNull(entity);

        DictValue updateEntity = new DictValue();
        updateEntity.setId(request.getId());
        updateEntity.setName(request.getName());
        this.updateById(updateEntity);

        msgService.sendUpdateDictMsg(dictService.info(entity.getDictId()));
    }

    /**
     * 删除
     */
    @Override
    public void deleteEntity(Long id) {
        this.removeById(id);
    }

}
